package cn.alcatraz.basic.service.impl;

import cn.alcatraz.basic.constant.BaseConstant;
import cn.alcatraz.basic.dto.LoginDto;
import cn.alcatraz.basic.exception.BusinessException;
import cn.alcatraz.basic.jwt.JwtUtils;
import cn.alcatraz.basic.jwt.RsaUtils;
import cn.alcatraz.basic.jwt.UserInfo;
import cn.alcatraz.basic.service.ILoginService;
import cn.alcatraz.basic.utils.AjaxResult;
import cn.alcatraz.basic.utils.HttpUtil;
import cn.alcatraz.basic.utils.MD5Utils;
import cn.alcatraz.basic.utils.StrUtils;
import cn.alcatraz.system.domain.Menu;
import cn.alcatraz.system.mapper.MenuMapper;
import cn.alcatraz.system.mapper.PermissionMapper;
import cn.alcatraz.user.domain.Logininfo;
import cn.alcatraz.user.domain.User;
import cn.alcatraz.user.domain.Wxuser;
import cn.alcatraz.user.dto.WechatDto;
import cn.alcatraz.user.mapper.LogininfoMapper;
import cn.alcatraz.user.mapper.UserMapper;
import cn.alcatraz.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPri;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    // 账号密码登录token方案
    /*@Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        // 1.参数为空校验
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(type)
        ){
            throw new BusinessException("参数不能为空！");
        }
        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null){
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 4.判断密码是否一致，需要加盐加密比较
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }*/

    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        // 1.参数为空校验
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(type)
        ){
            throw new BusinessException("参数不能为空！");
        }
        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadUsernameAndType(username, type);
        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null){
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 4.判断密码是否一致，需要加盐加密比较
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号密码错误，请重新输入！");
        }


        // 5.获取私钥进行加密
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPri).getFile());
        // 8.将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();

        // 6.根据Logininfo&menus&permissions加密之后得到JWT串
        UserInfo userInfo = new UserInfo();
        if ("0".equals(type)){
            // 1.如果是后台用户那么需要设置菜单权限和按钮权限到userInfo中
            List<String> permissions = permissionMapper.loadOwnerPermissionByLogininfoId(logininfo.getId());
            List<Menu> menus = menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
            map.put("permissions", permissions);
            map.put("menus", menus);
        }
        userInfo.setLogininfo(logininfo);
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);

        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");

        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }

    /**
     * @Title: wechat
     * @Description: 微信登录
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/10 14:32
     * @Parameters: [code]
     * @Return cn.itsource.basic.utils.AjaxResult
     */
    @Override
    public AjaxResult wechat(WechatDto wxDto) {
        // 1.非空校验
        if (StringUtils.isEmpty(wxDto.getCode())){
            throw new BusinessException("参数为空！");
        }
        // 2.根据code调用微信API获取access_token&openId
        String tokenUrl = BaseConstant.WechatConstant.TOKEN_URL
                .replace("APPID", BaseConstant.WechatConstant.APPID)
                .replace("SECRET", BaseConstant.WechatConstant.SECRET)
                .replace("CODE", wxDto.getCode());
        String jsonObjStr = HttpUtil.httpGet(tokenUrl);
        JSONObject jsonObj = JSONObject.parseObject(jsonObjStr);
        // 3.根据openId查询wxUser表，看微信用户是否存在并且绑定账号
        Wxuser wxuser = wxuserMapper.loadByOpenId(jsonObj.getString("openid"));
        // 3.1.存在并且绑定，让用户直接免密登录
        if (wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 5.生成UUID作为key
            String token = UUID.randomUUID().toString();
            // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            // 7.把Logininfo对象的敏感信息置为空，作为value
            logininfo.setSalt("");
            logininfo.setPassword("");
            // 8.将uuid&&logininfo存入到map中，返回给前端
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);
            return AjaxResult.myself().setResultObj(map);
        }
        // 3.2.不存在，传递access_token&openId到页面，并且success=false&message=nobinder
        /*new StringBuffer()
                .append("?accessToken=")
                .append(jsonObj.getString("access_token"))
                .append("&openId=")
                .append(jsonObj.getString("openid"));*/
        String paramStr = "?accessToken=" + jsonObj.getString("access_token") + "&openId=" + jsonObj.getString("openid");
        return AjaxResult.myself().setSuccess(false).setMessage("nobinder").setResultObj(paramStr);
    }

    /**
     * @Title: binder
     * @Description: 微信登录绑定账号
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/10 15:49
     * @Parameters: [wxDto]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    @Transactional
    public Map<String, Object> binder(WechatDto wxDto)              {
        // 1.非空校验
        String verifyCode = wxDto.getVerifyCode();
        String phone = wxDto.getPhone();
        String accessToken = wxDto.getAccessToken();
        String openId = wxDto.getOpenId();
        if (StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数异常！");
        }
        // 2.手机验证码校验
        // 1.为空校验
        String phoneCodeKey = BaseConstant.VerifyCodeConstant.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 3.判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 3.根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        // 3.1.不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {// 3.2.存在：查询Logininfo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 4.根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstant.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);
        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 5.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 6.返回成功登录map
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }


    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
